const User = require('../models/User')
const Order = require('../models/Order')
const Response = require('../utils/response')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config/config')

// ===== 管理员认证 =====

// 管理员登录
exports.adminLogin = async (req, res) => {
  try {
    const { username, password } = req.body

    if (!username || !password) {
      return Response.error(res, '用户名和密码不能为空', 400)
    }

    // 查询管理员用户
    const db = require('../config/db')
    const [users] = await db.execute(
      'SELECT * FROM jd_users WHERE username = ? AND is_admin = 1',
      [username]
    )

    if (users.length === 0) {
      return Response.error(res, '管理员账号不存在', 401)
    }

    const admin = users[0]

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, admin.password)
    if (!isPasswordValid) {
      return Response.error(res, '密码错误', 401)
    }

    // 生成 JWT token
    const token = jwt.sign(
      { 
        userId: admin.id, 
        username: admin.username,
        role: 'admin'
      },
      config.jwt.secret,
      { expiresIn: config.jwt.expire }
    )

    return Response.success(res, {
      token,
      admin: {
        id: admin.id,
        username: admin.username,
        email: admin.email,
        role: 'admin'
      }
    }, '登录成功')
  } catch (error) {
    console.error('管理员登录错误:', error)
    return Response.error(res, '登录失败', 500)
  }
}

// ===== 用户管理 =====

// 获取所有用户列表
exports.getAllUsers = async (req, res) => {
  console.log('=== getAllUsers 被调用 [VERSION 2.0] ===', req.query)
  try {
    const { page = 1, limit = 20, keyword = '' } = req.query
    const offset = (page - 1) * limit

    let sql = `
      SELECT 
        id, username, email, phone, avatar,
        CASE WHEN is_admin = 1 THEN 'admin' ELSE 'user' END as role,
        created_at
      FROM jd_users
      WHERE 1=1
    `
    const params = []

    if (keyword) {
      sql += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)'
      const searchTerm = `%${keyword}%`
      params.push(searchTerm, searchTerm, searchTerm)
    }

    // 获取总数
    const countSql = sql.replace(/SELECT[\s\S]*?FROM/, 'SELECT COUNT(*) as total FROM')
    const db = require('../config/db')
    const [countResult] = await db.execute(countSql, params)
    const total = countResult[0].total

    // 获取分页数据
    sql += ` ORDER BY created_at DESC LIMIT ${parseInt(limit)} OFFSET ${parseInt(offset)}`
    const [users] = await db.execute(sql, params)

    return Response.success(res, {
      users,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total
      }
    })
  } catch (error) {
    console.error('获取用户列表错误:', error.message)
    console.error('错误堆栈:', error.stack)
    return Response.error(res, '获取用户列表失败', 500)
  }
}

// 获取单个用户详情
exports.getUserById = async (req, res) => {
  try {
    const { id } = req.params
    const user = await User.findById(id)
    
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    return Response.success(res, user)
  } catch (error) {
    console.error('获取用户详情错误:', error)
    return Response.error(res, '获取用户详情失败', 500)
  }
}

// 更新用户信息
exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params
    const { email, phone, avatar, role } = req.body

    const user = await User.findById(id)
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    // 构建更新数据对象
    const updateData = { email, phone, avatar }
    
    // 如果提供了role，需要更新is_admin字段
    if (role !== undefined) {
      updateData.is_admin = role === 'admin' ? 1 : 0
    }

    await User.update(id, updateData)

    return Response.success(res, null, '用户信息更新成功')
  } catch (error) {
    console.error('更新用户信息错误:', error)
    return Response.error(res, '更新用户信息失败', 500)
  }
}

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params

    const user = await User.findById(id)
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    // 防止删除管理员自己
    if (parseInt(id) === req.userId) {
      return Response.error(res, '不能删除自己的账号', 400)
    }

    await User.delete(id)

    return Response.success(res, null, '用户已删除')
  } catch (error) {
    console.error('删除用户错误:', error)
    return Response.error(res, '删除用户失败', 500)
  }
}

// 重置用户密码
exports.resetPassword = async (req, res) => {
  try {
    const { id } = req.params
    const { newPassword = '123456' } = req.body

    const user = await User.findById(id)
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    await User.changePassword(id, newPassword)

    return Response.success(res, null, `密码已重置为: ${newPassword}`)
  } catch (error) {
    console.error('重置密码错误:', error)
    return Response.error(res, '重置密码失败', 500)
  }
}

// ===== 订单管理 =====

// 获取所有订单列表
exports.getAllOrders = async (req, res) => {
  try {
    const { page = 1, limit = 20, status = '', keyword = '' } = req.query
    const offset = (page - 1) * limit

    let sql = `
      SELECT 
        o.id, o.order_no, o.user_id, o.total_amount, o.actual_amount,
        o.status, o.receiver_address, o.created_at, o.updated_at,
        u.username
      FROM jd_orders o
      LEFT JOIN jd_users u ON o.user_id = u.id
      WHERE 1=1
    `
    const params = []

    if (status) {
      sql += ' AND o.status = ?'
      params.push(status)
    }

    if (keyword) {
      sql += ' AND (o.order_no LIKE ? OR u.username LIKE ? OR o.receiver_address LIKE ?)'
      const searchTerm = `%${keyword}%`
      params.push(searchTerm, searchTerm, searchTerm)
    }

    // 获取总数
    const countSql = sql.replace(/SELECT[\s\S]*?FROM/, 'SELECT COUNT(*) as total FROM')
    const db = require('../config/db')
    const [countResult] = await db.execute(countSql, params)
    const total = countResult[0].total

    // 获取分页数据
    sql += ` ORDER BY o.created_at DESC LIMIT ${parseInt(limit)} OFFSET ${parseInt(offset)}`
    const [orders] = await db.execute(sql, params)

    return Response.success(res, {
      orders,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total
      }
    })
  } catch (error) {
    console.error('获取订单列表错误:', error.message)
    console.error('错误堆栈:', error.stack)
    return Response.error(res, '获取订单列表失败', 500)
  }
}

// 获取订单详情
exports.getOrderById = async (req, res) => {
  try {
    const { id } = req.params
    const db = require('../config/db')

    // 获取订单基本信息
    const [orders] = await db.execute(`
      SELECT 
        o.*, u.username, u.email, u.phone
      FROM jd_orders o
      LEFT JOIN jd_users u ON o.user_id = u.id
      WHERE o.id = ?
    `, [id])

    if (orders.length === 0) {
      return Response.notFound(res, '订单不存在')
    }

    const order = orders[0]

    // 获取订单商品
    const [items] = await db.execute(`
      SELECT * FROM jd_order_items WHERE order_id = ?
    `, [id])

    order.items = items

    return Response.success(res, order)
  } catch (error) {
    console.error('获取订单详情错误:', error)
    return Response.error(res, '获取订单详情失败', 500)
  }
}

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
  try {
    const { id } = req.params
    const { status } = req.body

    const validStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled']
    if (!validStatuses.includes(status)) {
      return Response.error(res, '无效的订单状态', 400)
    }

    const db = require('../config/db')
    const [result] = await db.execute(
      'UPDATE jd_orders SET status = ?, updated_at = NOW() WHERE id = ?',
      [status, id]
    )

    if (result.affectedRows === 0) {
      return Response.notFound(res, '订单不存在')
    }

    return Response.success(res, null, '订单状态更新成功')
  } catch (error) {
    console.error('更新订单状态错误:', error)
    return Response.error(res, '更新订单状态失败', 500)
  }
}

// 删除订单
exports.deleteOrder = async (req, res) => {
  try {
    const { id } = req.params
    const db = require('../config/db')

    // 先删除订单商品
    await db.execute('DELETE FROM jd_order_items WHERE order_id = ?', [id])
    
    // 再删除订单
    const [result] = await db.execute('DELETE FROM jd_orders WHERE id = ?', [id])

    if (result.affectedRows === 0) {
      return Response.notFound(res, '订单不存在')
    }

    return Response.success(res, null, '订单已删除')
  } catch (error) {
    console.error('删除订单错误:', error)
    return Response.error(res, '删除订单失败', 500)
  }
}

// 获取订单统计
exports.getOrderStats = async (req, res) => {
  try {
    const db = require('../config/db')

    const [stats] = await db.execute(`
      SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid,
        SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) as shipped,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
        SUM(CASE WHEN status IN ('paid', 'shipped', 'completed') THEN actual_amount ELSE 0 END) as totalRevenue
      FROM jd_orders
    `)

    return Response.success(res, stats[0])
  } catch (error) {
    console.error('获取订单统计错误:', error)
    return Response.error(res, '获取订单统计失败', 500)
  }
}


